package org.korosoft.rusalad.syncnrun.cli;

import org.apache.commons.cli.CommandLine;
import org.korosoft.rusalad.syncnrun.Main;

import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * Version command.
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class CliVersion extends CliCommand {

    public static final String SNAPSHOT_SUFFIX = "-SNAPSHOT";

    public CliVersion() {
        super("version", "Displays version information");
        options.addOption("o", "offline", false, "Do not perform check for update.");
    }

    @Override
    protected void doExecute(CommandLine commandLine) throws Exception {
        Properties properties = new Properties();
        InputStream stream = getClass().getResourceAsStream("/versions.properties");
        properties.load(stream);
        stream.close();
        String currentVersion = properties.get("syncnrun.current.version").toString();
        String latestVersionUrl = properties.get("syncnrun.latest.stable.version.url").toString();
        System.out.println("Syncnrun version: " + currentVersion);
        boolean snapshot = false;
        if (currentVersion.endsWith(SNAPSHOT_SUFFIX)) {
            currentVersion = currentVersion.replace(SNAPSHOT_SUFFIX, "");
            snapshot = true;
        }
        if (!commandLine.hasOption("o")) {
            InputStream inStream = new URL(latestVersionUrl).openStream();
            properties.load(inStream);
            inStream.close();
            String latestStable = properties.get("rusalad.latest.stable.version").toString();
            System.out.println("Syncnrun latest stable version: " + latestStable);
            if (currentVersion.compareToIgnoreCase(latestStable) < 0 || (currentVersion.compareToIgnoreCase(latestStable) == 0 && snapshot)) {
                throw new RuntimeException("UPDATE IS AVAILABLE. Visit http://code.google.com/p/russian-salad/downloads/list page.");
            } else {
                System.out.println("Syncnrun is up to date");
            }
        }
    }
}
